package com.weifly.weistock.core.util.visitor;


import java.util.*;

/**
 * 前向visitor
 *
 * @author weifly
 * @since 2021/1/22
 */
public class PreviousVisitor<E> implements Iterator<E> {

    private ListIterator<DataListContainer<E>> containerIter;
    private ListIterator<E> dataIter;

    public PreviousVisitor(Collection<DataListContainer<E>> containers) {
        this.containerIter = new ArrayList<DataListContainer<E>>(containers).listIterator(containers.size());
    }

    @Override
    public boolean hasNext() {
        while (this.dataIter == null || !this.dataIter.hasPrevious()) {
            // 获得新的dataIter
            this.dataIter = this.takeNewDataIter();
            if (this.dataIter == null) {
                return false;
            }
        }
        return true;
    }

    private ListIterator<E> takeNewDataIter() {
        while (this.containerIter.hasPrevious()) {
            List<E> dataList = this.containerIter.previous().getDataList();
            if (dataList.size() > 0) {
                return dataList.listIterator(dataList.size());
            }
        }
        return null;
    }

    @Override
    public E next() {
        return this.dataIter.previous();
    }
}
